package controllers;

import connectivity.Dbmanager;
import connectivity.QueryManager;
import java.io.*;
import java.util.LinkedList;
import java.util.List;
import javax.servlet.*;
import javax.servlet.http.*;
import models.User;
import models.Course;

public class SubscribeCourseTeacherController extends HttpServlet {

    private int courseid;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        if (request.getParameter("courseid") == null) {

            Dbmanager dbManager = new Dbmanager();
            dbManager.openConnection();
            QueryManager queryManager = new QueryManager(dbManager);
            HttpSession sessie = request.getSession();
            User user = (User) sessie.getAttribute("gebruikerinfo");
            LinkedList<Course> allcourses = queryManager.getAllCourses();
            LinkedList<Course> teachercourses = queryManager.getAllTeacherCourses(user.getID());
            LinkedList<Course> subscribecourses = new LinkedList<Course>();
            Boolean allsubscribed;


            for (int i = 0; i < allcourses.size(); i++) {
                allsubscribed = false;
                
                for (int j = 0; j < teachercourses.size(); j++) {
                    Course tempcourse1 = allcourses.get(i);
                    Course tempcourse2 = teachercourses.get(j);
                    if (tempcourse1.getCourseID() == tempcourse2.getCourseID()) {
                        allsubscribed = true;
                    }
                }
                if (allsubscribed == false) {
                    subscribecourses.add(allcourses.get(i));
                }
            }

            request.setAttribute("coursesUitSessie", subscribecourses);

            dbManager.closeConnection();

            RequestDispatcher dispatcher = request.getRequestDispatcher("/subscribe_course_teacher.jsp");
            dispatcher.forward(request, response);
        } else {
            courseid = Integer.parseInt(request.getParameter("courseid"));
            doPost(request, response);
        }

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        Dbmanager dbManager = new Dbmanager();
        dbManager.openConnection();
        QueryManager queryManager = new QueryManager(dbManager);
        HttpSession sessie = request.getSession();

        User user = (User) sessie.getAttribute("gebruikerinfo");

        if (user.getLevel() > 1) {
            queryManager.addteachertocourse(user.getID(), courseid);
        }

        dbManager.closeConnection();
        response.sendRedirect("subscribe_course_teacher");

    }
}
